import * as pdfjsLib from 'pdfjs-dist'
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs'

const getPdfPageBlobUrls = async (arrayBuffer: ArrayBuffer) => {
  try {
    const pdfDoc: pdfjsLib.PDFDocumentProxy = await pdfjsLib.getDocument(arrayBuffer).promise     // 加载PDF文档
    const pageNum = pdfDoc.numPages // 获取页面数量

    const promises = Array(pageNum).fill(undefined).map(async (_, pageIndex) => {
      pageIndex += 1 // 页面索引从1开始
      const page = await pdfDoc.getPage(pageIndex) // 获取页面
      const viewport = page.getViewport({ scale: 1.0 }) // 设置视图大小
      // 创建Canvas元素
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      canvas.width = viewport.width
      canvas.height = viewport.height
      // 渲染页面到Canvas
      if (context) {
        await page.render({ canvasContext: context, viewport: viewport, canvas }).promise
      } else {
        throw new Error('无法获取Canvas上下文')
      }

      page.cleanup() // 清理内存

      return new Promise((resolve) => {
        canvas.toBlob((blob) => {
          resolve(blob ? URL.createObjectURL(blob) : '')
        }, 'image/png')
      }) as Promise<string>
    })

    // await pdfDoc.destroy() // 销毁PDF文档对象

    return promises
  } catch (error) {
    console.error('获取PDF页面Blob失败:', error)
    throw new Error('PDF封面加载失败')
  }
}

export default async (arrayBuffer: ArrayBuffer) => await getPdfPageBlobUrls(arrayBuffer)
